from qcloudsms_py import SmsSingleSender
from luffyapi.utils.logger import log  # 导入日志模块
from . import settings
import random


# 生成一个四位随机验证码
def get_code():
    s_code = ''
    for i in range(4):
        s_code += str(random.randint(0, 9))
    return s_code


# 发送短信
def send_message(phone_numbers, code):
    ssender = SmsSingleSender(settings.appid, settings.appkey)
    params = [code, '3']
    try:
        result = ssender.send_with_param(86, phone_numbers,
                                         settings.template_id, params, sign=settings.sms_sign,
                                         extend="", ext="")
        if result.get('result') == 0:
            return True  # result为0表示短息发送成功
        else:
            return False
    except Exception as e:
        log.error('手机号：%s 短信发送失败，错误信息：%s' % (phone_numbers, str(e)))  # 记录错误日志
